<template>
	<view>
		<view class="board" :style="{width:width+'px',height:height+'px'}">
			<view class="scrolling-text" @tap="clickBoard">
				<view class="text-item">
					{{board && board.title || '本群未设置运财宝'}}
				</view>
			</view>
		</view>
		<!-- <up-modal v-if="board && showBoardText && showModal" :show="showBoardText" :title="board.title"
			:content='board.content' @confirm="showBoardText = !showBoardText">
		</up-modal> -->

		<up-popup :show="showBoardText" mode="center" :closeOnClickOverlay="false"
			@close="showBoardText = !showBoardText" :safeAreaInsetBottom="false" @open="" :round="8">
			<view class="popup-box">
				<swiper :current="sortedCurrent" @change="handleSwiperChange" style="height: 100%;">

					<!-- 动态生成排序后的 swiper-item -->
					<swiper-item v-for="(item, index) in orderedSwipers" :key="item.type" style="height: 100%;">
						<scroll-view class="scroll-content" scroll-y v-if="item.type === 0">
							<!-- 根据类型渲染对应内容 -->
							<view v-if="item.type === 0">
								<!-- 文本信息内容 -->
								<view v-if="showNormal">
									<text class="title">{{board.title}}</text>
									<!-- <text v-html="formatContent(board.content)"></text> -->
									<text class="text-sm-Regular">{{board.content}}</text>
									<view class="fc">
										<image v-for="(img, i) in board.pictures" :src="img" class="pimg"
											@click="previewImage(i)" :key="i"></image>
									</view>
								</view>
								<view v-else>
									<view v-for="(item, idx) in list" :key="idx">
										<view v-if="item.type===0">
											<text class="title">{{item.title}}</text>
											<!-- <text v-html="formatContent(item.content)"></text> -->
											<text class="text-sm-Regular">{{item.content}}</text>
											<view class="fc">
												<image v-for="(img, i) in item.pictures" :src="img" class="pimg"
													@click="previewCompanyImage(i, idx)" :key="i"></image>
											</view>
											<up-line margin="30rpx 0"></up-line>
										</view>
									</view>
								</view>
							</view>
						</scroll-view>

						<scroll-view class="scroll-content" scroll-y v-else-if="item.type === 1">
							<!-- 商品橱窗内容 -->
							<view class="title" style="margin-bottom: 10rpx;">商品栏</view>
							<view class="commo-content">
								<view class="content-item" v-for="(product, idx) in products" :key="idx"
									@click="goCommodityDetail(product.productId)">
									<image class="img" :src="product.masterImage"></image>
									<view class="commo-font">{{product.name}}</view>
									<view class="content-item-xia">
										<view class="commo-price">￥{{fenyuan2(product.price)}}起</view>
										<!-- <view class="commo-num">已售{{product.sales}}</view> -->
									</view>
								</view>
							</view>
						</scroll-view>

						<view v-else-if="item.type === 2" style="height: 100%;">
							<!-- 小程序跳转 -->
							<view class="jump-container">
								<view v-if="miniProgram">
									<button @click="tiaozhuangwaibu(miniProgram.content)">跳转小程序</button>
									<text class="beizhu">点击即可跳转到对应的小程序浏览</text>
								</view>
								<view v-else>
									<text class="beizhu">暂无设置小程序</text>
								</view>
							</view>
						</view>

						<view v-else-if="item.type === 3" style="height: 100%;">
							<!-- 链接复制 -->
							<view class="link-container">
								<view v-if="link">
									<button @click="copyLink(link.content)">复制链接</button>
									<text class="beizhu">点击即可复制链接(因小程序限制需自行前往浏览器)</text>
								</view>
								<view v-else>
									<text class="beizhu">暂无设置链接</text>
								</view>
							</view>
						</view>

						<view v-else-if="item.type === 4" style="height: 100%;">
							<!-- 本地生活 -->
							<view class="title" style="margin-bottom: 20rpx;">本地生活</view>
							<view class="life-container">
								<view class="life" v-for="(item,index) in life" :key="index">
									<view class="life-left">
										<image class="img" :src="item.img" alt=""></image>
									</view>
									<view class="life-right">
										<view class="right-top">
											<view class="left">
												<text class="name">{{item.name}}</text>
												<text class="location">{{item.location}}</text>
												<view style="width: 100%;" class="tag-list">
													<view v-for="(it,i) in item.tag">
														<text class="tag">{{it}}</text>
													</view>
												</view>
											</view>
											<view class="right">
												<button>拨打</button>
											</view>
										</view>
										<view class="right-bottom">
											<text class="price">￥{{item.price}}</text>
											<text class="message">{{item.message}}</text>
										</view>
									</view>
								</view>
							</view>
						</view>
					</swiper-item>
				</swiper>
				<button class="btn" @click="showBoardText = !showBoardText">关闭</button>
			</view>
		</up-popup>
	</view>
</template>

<script>
	export default {
		name: "board",

		props: {
			modelValue: {
				type: [String, Number],
			},
			width: {
				type: [String, Number]
			},
			height: {
				type: [String, Number],
				default: '25'
			},
			showModal: {
				type: Boolean,
				default: false
			},
			showList: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				current: 0,
				showBoardText: false,
				board: null, // 滚动文本对象
				miniProgram: null, //小程序
				link: null, //链接
				pictures: [],
				formData: {},
				pageNum: 1,
				pageSize: 20,
				list: [],
				company: [],
				order: [], //存放排序数组
				currentType: 0, // 当前激活的类型
				showNormal: true, //是否启动默认的文本信息 默认是启动的
				products: [ // 商品橱窗数据
					{
						masterImage: '/static/tarbar/business-true.png',
						name: '湖南正宗火焙刁子鱼1 湖南正宗火焙刁子鱼1',
						price: 3900,
						sales: 169
					},
					{
						masterImage: 'https://file.dgyxy.com/resource/images/gCaPae4zjp_small.jpg',
						name: '湖南正宗火焙刁子鱼2',
						price: 4900,
						sales: 89
					}
				],
				life: [{
						img: 'https://file.dgyxy.com/resource/icon/AiLogo.jpg',
						name: '松鼠ai智学馆',
						location: "东莞",
						price: "9.9",
						tag: "热门，人气",
						message: "两节体验课程，从小学到高中，双师辅导，一对一教学，强化薄弱知识点，高效提升成绩。"
					},
					{
						img: 'https://file.dgyxy.com/resource/icon/AiLogo2.jpg',
						name: '松鼠ai智学馆',
						location: "东莞",
						price: "29.9",
						tag: "热门，人气，教培",
						message: "六节体验课程，从小学到高中，双师辅导，一对一教学，强化薄弱知识点，高效提升成绩。"
					}
				],
				rules: {
					name: {
						rules: [{
								required: true,
								errorMessage: '请填写公司名称',
							},
							{
								minLength: 3,
								maxLength: 30,
								errorMessage: '{label}长度在 {minLength} 到 {maxLength} 个字符',
							}
						],
					},
					info: {
						rules: [{
							required: true,
							errorMessage: '请填写简介',
						}, ],
					},
					user: {
						rules: [{
							required: true,
							errorMessage: '请填写联系人',
						}, ],
					},
					phone: {
						rules: [{
							required: true,
							errorMessage: '请填写电话',
						}, ],
					},
					address: {
						rules: [{
							required: true,
							errorMessage: '请填写地址',
						}, ],
					}
				}
			};
		},
		async mounted() {
			uni.$on('refreshBoard', this.handleRefresh)
		},
		async beforeDestroy() {
			// 记得移除监听，避免内存泄漏
			uni.$off('refreshBoard', this.handleRefresh)
		},

		computed: {
			// 核心排序逻辑
			orderedSwipers() {
				const typeMap = {
					0: {
						title: '文本信息',
						priority: 0
					},
					1: {
						title: '商品橱窗',
						priority: 1
					},
					2: {
						title: '小程序跳转',
						priority: 2
					},
					3: {
						title: '链接复制',
						priority: 3
					},
					4: {
						title: '本地生活',
						priority: 4
					}
				};

				// 按order数组顺序生成新序列
				return this.order
					.map(type => ({
						type,
						...typeMap[type]
					}))
					.filter(item => item)
			},

			// 动态计算初始 currentType
			sortedCurrent() {
				// 如果没有有效类型则默认返回0
				const firstValidType = this.orderedSwipers[0]?.type || 0;
				return this.orderedSwipers.findIndex(
					item => item.type === firstValidType
				);
			}
		},
		watch: {
			// 监听弹窗显示状态
			showBoardText(newVal) {
				if (newVal) {
					this.$nextTick(() => {
						// 每次打开弹窗时强制重置到第一个面板
						this.currentType = this.orderedSwipers[0]?.type || 0;
					});
				}
			}
		},
		methods: {
			// 处理swiper切换
			handleSwiperChange(e) {
				// 根据新索引获取类型
				const newType = this.orderedSwipers[e.detail.current].type;

				// 同步更新currentType
				this.currentType = newType;
			},
			goCommodityDetail(id) {
				uni.navigateTo({
					url: "/pageSubOne/CommodityDetail/CommodityDetail?id=" + id
				})
			},
			changeItem(e) {
				this.current = e.detail.current;
			},
			// 图片预览
			previewImage(index) {
				uni.previewImage({
					urls: this.board.pictures,
					current: index
				});
			},
			// 公司图片预览
			previewCompanyImage(i, index) {
				uni.previewImage({
					urls: this.list[index].pictures,
					current: i
				});
			},
			// 图片上传
			onUnloadImageSuccess(file, res) {
				this.pictures.push(res.data.originUrl)
			},
			// 删除图片
			deleteImg(index) {
				for (let i = this.pictures.length - 1; i >= 0; i--) {
					if (i === index) {
						this.pictures.splice(index, 1)
					}
				}
			},
			submitForm() {
				this.$refs.form.validate().then(res => {
					if (this.pictures.length == 0) {
						uni.showToast({
							title: "请上传图片",
							icon: "none"
						})
					}
					console.log('表单数据信息：', res);
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			},
			getData() {
				return new Promise((resolve, reject) => {
					// 加载群滚动文本
					this.$http({
						url: "/group/board/last",
						method: "GET",
						data: {
							groupId: this.modelValue
						}
					}).then(res => {
						console.log(res)
						this.board = res
						resolve(res)
					}).catch(err => {
						reject(err)
					})

					if (this.showList) {
						// 加载群运财宝内容
						this.$http({
							url: "/group/board/list",
							method: "GET",
							data: {
								groupId: this.modelValue,
								// pageNum: this.pageNum,
								pageNum: this.list.pageNum || 1,
								pageSize: this.list.pageSize || 20
							}
						}).then(res => {
							let xcx = []
							let lj = []
							res.list.forEach(item => {
								if (item.type === 0) {
									this.showNormal = false
								}
								if (item.type === 4) {
									xcx.push(item)
								}
								if (item.type === 5) {
									this.products = item.products
								}
								if (item.type === 1) {
									lj.push(item)
								}
							})
							this.miniProgram = xcx[0]
							this.link = lj[0]
							this.list = res.list
							console.log(this.list)
							resolve(res)
						}).catch(err => {
							reject(err)
						})

						//加载群运财宝顺序
						this.$http({
							url: `/group/config/${this.modelValue}`,
							method: "GET",
						}).then(res => {
							console.log(res)
							this.order = res.groupBoardOrder
							// this.order = [0, 1, 2, 3, 4]
							resolve(res)
						}).catch(err => {
							reject(err)
						})

						this.life.forEach(item => {
							if (typeof item.tag === 'string') {
								item.tag = item.tag.split("，");
							}
						});
					}


				})
			},
			tiaozhuangwaibu(appId) {
				uni.navigateToMiniProgram({
					appId: appId,
					//appId: 'wxc2d8d319dfc12a95',
					success(res) {
						console.log('跳转成功')
					},
					fail(err) {
						if (err.errMsg == "navigateToMiniProgram:fail invalid appid") {
							uni.showToast({
								title: "小程序appId失效或输入错误，请重试或换个小程序试试吧~",
								icon: "none"
							})
						}
					}
				})
			},
			copyLink(link) {
				this.copyText(link)
			},
			async clickBoard() {

				await this.getData()
				if (!this.board) {
					return
				}
				if (this.board.type == 0) {
					this.showBoardText = !this.showBoardText
				} else if (this.board.type == 1) {
					// let url = 'https://www.zs.gov.cn/fsz/';
					// uni.navigateTo({
					// 	url: '/pageSubOne/webView/webView?url=' + encodeURIComponent(url)
					// });
					// #ifdef H5
					window.open(this.board.content)
					// #endif
					// #ifndef H5
					// this.copyText(this.board.content)
					this.showBoardText = !this.showBoardText
					// #endif
				} else if (this.board.type == 2) {
					this.goPage("/pageSubOne/group/group-introduction?id=" + this.modelValue)
				} else if (this.board.type == 3) {
					this.showBoardText = !this.showBoardText
				} else if (this.board.type == 4) {
					// this.tiaozhuangwaibu(this.board.content)
					this.showBoardText = !this.showBoardText
				}
			},
			async handleRefresh() {
				await this.getData()
			}
		},

		watch: {
			// 监听groupId变化
			modelValue: {
				handler(newVal) {
					if (newVal) {
						this.getData()
					}
				},
				immediate: true
			}
		}



	}
</script>

<style lang="scss" scoped>
	.board {
		background-color: transparent;

		.scrolling-text {
			display: flex;
			overflow: hidden;
			white-space: nowrap;
			position: relative;
			width: 100%;
			background-color: #ABEFC6;
			color: #F04438;
			border-radius: 4px;
		}

		.text-item {
			display: inline-block;
			padding-left: 50%;
			/* 根据需要调整 */
			animation: scroll 10s linear infinite;
		}

		@keyframes scroll {
			0% {
				transform: translateX(0);
			}

			100% {
				transform: translateX(-100%);
			}
		}
	}

	:deep(.u-popup__content) {
		width: 90%;
	}

	:deep(.u-transition.u-fade-enter-to.u-fade-enter-active) {
		z-index: 100 !important;
	}

	:deep(.u-transition.u-fade-zoom-enter-to.u-fade-zoom-enter-active) {
		z-index: 100 !important;
	}

	.popup-box {
		display: flex;
		flex-direction: column;
		width: 82vw;
		gap: 24rpx;
		padding: 24rpx 32rpx;
		height: 80vh;

		.beizhu {
			color: $warning-500;
			margin-top: 20rpx;
		}

		.companyBac {
			background-color: #dedede !important;
		}


		.company {
			background-color: #fff;
			padding: 24rpx 0;
			display: flex;
			flex-direction: column;
			justify-content: center;
			gap: 24rpx;
			margin-bottom: 20rpx;

			.name,
			.user,
			.phone,
			.address {
				border-bottom: 1rpx solid #e7e7e7;
				padding-bottom: 24rpx;
			}

			.user {
				text:last-child {
					margin-left: 28rpx;
				}
			}

			.signature {
				display: flex;
				flex-direction: column;
				gap: 24rpx;
				justify-content: center;
				border-bottom: 1rpx solid #e7e7e7;
				padding-bottom: 24rpx;

				text:last-child {
					color: #7e7e7e;
					font-size: 28rpx;
				}
			}

			.imgList {
				width: 100%;
				display: grid;
				grid-template-columns: repeat(auto-fill, minmax(180rpx, 1fr));
				text-align: center;

				.img {
					width: 180rpx;
					height: 180rpx;
					border-radius: 16rpx;
				}
			}

			.phone,
			.address {
				text:last-child {
					margin-left: 62rpx;
				}
			}
		}

		.scroll-content {
			height: 100%;
			//max-height: 75vh;
			/* 设置最大高度 */
			overflow-y: auto;
			/* 允许垂直滚动 */
		}


		.title {
			display: flex;
			justify-content: center;
			align-items: center;
			font-weight: bold;
			color: $gray-600;
			padding-bottom: 10rpx 0;
		}

		.fc {
			display: grid;
			grid-template-columns: repeat(auto-fill, minmax(140rpx, 1fr));
			text-align: center;
			padding-bottom: 10rpx;

			.pimg {
				width: 140rpx;
				height: 140rpx;
				margin-top: 15rpx;
			}
		}

		.btn {
			background-color: $white;
			color: $brand-500;
			font-size: 30rpx;
			width: 100%;
		}

		.form {
			margin-top: 20rpx;

			.imgList {
				display: grid;
				/* #ifndef APP-PLUS */
				grid-template-columns: repeat(auto-fill, minmax(72px, 1fr));
				/* #endif */
				/* #ifdef APP-PLUS */
				grid-template-columns: repeat(auto-fill, minmax(140rpx, 1fr));
				/* #endif */
				gap: 8rpx;
				margin-top: 24rpx;
			}

			.img-container {
				position: relative;

				.pimg {
					width: 140rpx;
					height: 140rpx;
					position: relative;
				}

				.imgclose {
					position: absolute;
					top: -20rpx;
					left: 110rpx;
					z-index: 100;
				}
			}

			.pic-add {
				background-color: $gray-100;
				width: 140rpx;
				height: 140rpx;
				border-radius: 16rpx;
				grid-row: span 1;
				/* 确保上传按钮占据一个单元格 */

				.box {
					width: 100%;
					height: 100%;
					display: flex;
					justify-content: center;
					align-items: center;
					flex-direction: column;
					gap: 16rpx;
				}
			}

			.photo {
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-size: 14px;
				color: #606266;
				margin-bottom: 20rpx;
			}

			.title {
				font-size: 28rpx;
				margin: 20rpx;
			}
		}
	}

	.commo-content {
		//width: 100%;
		display: flex;
		flex-wrap: wrap;

		.content-item {
			width: 38vw;
			padding: 10rpx;
			text-align: center;

			.img {
				width: 270rpx;
				border-radius: 20rpx;
				height: 270rpx;
				text-align: center;
			}

			.commo-font {
				display: -webkit-box;
				-webkit-line-clamp: 1;
				-webkit-box-orient: vertical;
				overflow: hidden;
				text-overflow: ellipsis;
				font-size: 26rpx;
				color: black;
				text-align: left;
			}

			.content-item-xia {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 10rpx;

				.commo-price {
					font-size: 23rpx;
					font-weight: bold;
					color: red;
				}

				.commo-num {
					font-size: 12rpx;
					color: gainsboro;
				}
			}
		}
	}

	.jump-container {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 100%;
		width: 100%;
	}

	.link-container {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 100%;
		width: 100%;
	}

	.life-container {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		height: 100%;
		width: 100%;

		.life {

			display: flex;
			gap: 12rpx;
			// align-items: center;

			.life-left {
				.img {
					width: 160rpx;
					height: 160rpx;
					border-radius: 20rpx;
				}
			}

			.life-right {
				width: 100%;
				display: flex;
				flex-direction: column;
				gap: 12rpx;

				.right-top {
					// width: 100%;
					display: flex;
					justify-content: space-between;
					align-items: center;

					.left {
						display: flex;
						flex-direction: column;
						gap: 6rpx;

						.name {
							// width: 100%;
							display: -webkit-box;
							-webkit-line-clamp: 1;
							-webkit-box-orient: vertical;
							overflow: hidden;
							text-overflow: ellipsis;
						}

						.location {
							color: gray;
							font-size: 26rpx;
						}

						.tag-list {
							display: flex;
							align-items: center;
							gap: 12rpx;
						}

						.tag {
							border: 1rpx solid $error-500;
							color: $error-500;
							border-radius: 20rpx;
							font-size: 26rpx;
							padding: 6rpx;
						}
					}

					.right {
						margin-right: 2rpx;

						button {
							width: 130rpx;
							background-color: $brand-500;
							color: $white;
							border-radius: 50rpx;
							font-size: 28rpx;
						}
					}
				}

				.right-bottom {
					display: flex;
					gap: 10rpx;

					.price {
						color: $error-500;
						font-size: 29rpx;
					}

					.message {
						width: 100%;
						font-size: 28rpx;
						display: -webkit-box;
						-webkit-line-clamp: 1;
						-webkit-box-orient: vertical;
						overflow: hidden;
						text-overflow: ellipsis;
					}
				}
			}
		}
	}
</style>